"""
缩略图查看器组件
"""

import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
from typing import List, Optional, Callable, Set
import threading

from ...utils.logger import Logger


class ThumbnailViewer(ttk.Frame):
    """缩略图查看器"""
    
    def __init__(self, parent, logger: Optional[Logger] = None, **kwargs):
        super().__init__(parent, **kwargs)
        
        self.logger = logger or Logger("ThumbnailViewer")
        self.thumbnails = []
        self.selected_pages: Set[int] = set()
        self.thumbnail_widgets = []
        self.selection_callback: Optional[Callable] = None
        
        # 配置参数
        self.thumbnail_width = 220
        self.thumbnail_height = 310
        self.columns = 4
        self.padding = 10
        
        self._create_widgets()
        self._bind_events()
    
    def _create_widgets(self):
        """创建组件"""
        # 创建滚动区域
        self.canvas = tk.Canvas(self, bg='white')
        self.scrollbar = ttk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
        self.scrollable_frame = ttk.Frame(self.canvas)
        
        # 配置滚动
        self.scrollable_frame.bind(
            "<Configure>",
            lambda e: self.canvas.configure(scrollregion=self.canvas.bbox("all"))
        )
        
        self.canvas.create_window((0, 0), window=self.scrollable_frame, anchor="nw")
        self.canvas.configure(yscrollcommand=self.scrollbar.set)
        
        # 布局
        self.canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        self.scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
    
    def _bind_events(self):
        """绑定事件"""
        self.canvas.bind_all("<MouseWheel>", self._on_mousewheel)
        self.bind("<Configure>", self._on_resize)
    
    def _on_mousewheel(self, event):
        """处理鼠标滚轮"""
        if event.delta:
            self.canvas.yview_scroll(-1 * (event.delta // abs(event.delta)), "units")
    
    def _on_resize(self, event):
        """处理窗口大小变化"""
        if event.widget == self:
            self._update_layout()
    
    def set_thumbnails(self, thumbnails: List[Image.Image]):
        """设置缩略图列表"""
        self.thumbnails = thumbnails
        self.selected_pages.clear()
        self._update_display()
    
    def _update_display(self):
        """更新显示"""
        # 清空现有组件
        for widget in self.scrollable_frame.winfo_children():
            widget.destroy()
        self.thumbnail_widgets.clear()
        
        if not self.thumbnails:
            return
        
        # 计算列数
        canvas_width = self.canvas.winfo_width()
        if canvas_width > 1:
            self.columns = max(1, (canvas_width - 20) // (self.thumbnail_width + self.padding))
        
        # 创建缩略图组件
        for i, thumbnail in enumerate(self.thumbnails):
            self._create_thumbnail_widget(i, thumbnail)
        
        # 配置网格权重
        for col in range(self.columns):
            self.scrollable_frame.columnconfigure(col, weight=1)
    
    def _create_thumbnail_widget(self, page_index: int, thumbnail: Image.Image):
        """创建单个缩略图组件"""
        page_num = page_index + 1
        row = page_index // self.columns
        col = page_index % self.columns
        
        # 创建框架
        frame = ttk.Frame(self.scrollable_frame, relief="groove", borderwidth=2)
        frame.grid(row=row, column=col, padx=self.padding//2, pady=self.padding//2, sticky="nsew")
        
        # 创建图像标签
        photo = ImageTk.PhotoImage(thumbnail)
        img_label = ttk.Label(frame, image=photo)
        img_label.image = photo  # 保持引用
        img_label.pack(pady=5)
        
        # 页码标签
        page_label = ttk.Label(frame, text=f"第 {page_num} 页")
        page_label.pack()
        
        # 选择复选框
        var = tk.BooleanVar()
        checkbox = ttk.Checkbutton(
            frame,
            variable=var,
            command=lambda p=page_num, v=var: self._on_selection_change(p, v)
        )
        checkbox.pack(pady=5)
        
        # 保存组件引用
        widget_info = {
            'frame': frame,
            'image_label': img_label,
            'page_label': page_label,
            'checkbox': checkbox,
            'var': var,
            'page_num': page_num
        }
        self.thumbnail_widgets.append(widget_info)
        
        # 绑定点击事件
        for widget in [frame, img_label, page_label]:
            widget.bind("<Button-1>", lambda e, p=page_num: self._toggle_selection(p))
    
    def _on_selection_change(self, page_num: int, var: tk.BooleanVar):
        """处理选择变化"""
        if var.get():
            self.selected_pages.add(page_num)
        else:
            self.selected_pages.discard(page_num)
        
        if self.selection_callback:
            self.selection_callback(self.selected_pages.copy())
    
    def _toggle_selection(self, page_num: int):
        """切换页面选择状态"""
        for widget_info in self.thumbnail_widgets:
            if widget_info['page_num'] == page_num:
                current_value = widget_info['var'].get()
                widget_info['var'].set(not current_value)
                self._on_selection_change(page_num, widget_info['var'])
                break
    
    def select_all(self):
        """全选"""
        for widget_info in self.thumbnail_widgets:
            widget_info['var'].set(True)
            self.selected_pages.add(widget_info['page_num'])
        
        if self.selection_callback:
            self.selection_callback(self.selected_pages.copy())
    
    def select_none(self):
        """取消全选"""
        for widget_info in self.thumbnail_widgets:
            widget_info['var'].set(False)
        
        self.selected_pages.clear()
        
        if self.selection_callback:
            self.selection_callback(self.selected_pages.copy())
    
    def invert_selection(self):
        """反选"""
        for widget_info in self.thumbnail_widgets:
            current_value = widget_info['var'].get()
            widget_info['var'].set(not current_value)
            
            page_num = widget_info['page_num']
            if current_value:
                self.selected_pages.discard(page_num)
            else:
                self.selected_pages.add(page_num)
        
        if self.selection_callback:
            self.selection_callback(self.selected_pages.copy())
    
    def get_selected_pages(self) -> Set[int]:
        """获取选中的页面"""
        return self.selected_pages.copy()
    
    def set_selection_callback(self, callback: Callable[[Set[int]], None]):
        """设置选择变化回调"""
        self.selection_callback = callback
    
    def _update_layout(self):
        """更新布局"""
        if self.thumbnails:
            # 延迟更新，避免频繁重绘
            self.after(100, self._update_display)
    
    def clear(self):
        """清空内容"""
        self.thumbnails.clear()
        self.selected_pages.clear()
        
        for widget in self.scrollable_frame.winfo_children():
            widget.destroy()
        self.thumbnail_widgets.clear()
